package com.leoman.spinningmachine.tab3;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.google.gson.reflect.TypeToken;
import com.leoman.helper.HelperConstant;
import com.leoman.helper.photo.PhotoHelper;
import com.leoman.helper.util.AppManager;
import com.leoman.helper.util.FrescoUtil;
import com.leoman.helper.util.ImageUtils;
import com.leoman.helper.util.LogUtil;
import com.leoman.helper.util.UriUtil;
import com.leoman.spinningmachine.R;
import com.leoman.spinningmachine.base.BaseActivity;
import com.leoman.spinningmachine.bean.UserPhoto;
import com.leoman.spinningmachine.constant.Constant;
import com.leoman.spinningmachine.constant.Urls;
import com.leoman.spinningmachine.http.APICallback;
import com.leoman.spinningmachine.http.APIResponse;
import com.leoman.spinningmachine.http.WebServiceApi;
import com.leoman.spinningmachine.login.LoginActivity;
import com.leoman.spinningmachine.util.SharedPreferencesUtils;
import com.spurs.retrofit.APIClient;

import java.io.File;
import java.io.FileNotFoundException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

import static com.leoman.spinningmachine.constant.Urls.HEAD_IMAGE;

/**
 * Created by Administrator on 2018-05-07.
 */
public class UserSettingActivity extends BaseActivity {
    @BindView(R.id.iv_pic)
    SimpleDraweeView iv_pic;

    @BindView(R.id.rl_setting_user_photo)
    RelativeLayout rl_setting_user_photo;

    @BindView(R.id.rl_setting1)
    RelativeLayout rl_setting1;

    @BindView(R.id.rl_setting2)
    RelativeLayout rl_setting2;

    @BindView(R.id.rl_setting3)
    RelativeLayout rl_setting3;

    @BindView(R.id.rl_setting4)
    RelativeLayout rl_setting4;
    @BindView(R.id.login_out)
    TextView login_out;

    private TextView tv_right_nickname;
    private TextView tv_right_bm;
    private TextView tv_right_phone;
    private TextView tv_right_gh;
    private View photoView;
    private AlertDialog dialog;
    private Dialog alertDialog;
    private String picUrl;
    private PhotoHelper photoHelper;

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.ac_user_setting;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        AppManager.getInstance().addActivity(this);
        initTitle("个人设置");

        Log.e("----进入个人设置----", "执行");
        Log.e("-----个人设置页面头像-----", SharedPreferencesUtils.getInstance().getString(Constant.HEADPATH));
        FrescoUtil.setImg(this, iv_pic, HEAD_IMAGE + SharedPreferencesUtils.getInstance().getString(Constant.HEADPATH));
        ((TextView) rl_setting1.findViewById(R.id.tv_left)).setText("昵称");
        ((TextView) rl_setting2.findViewById(R.id.tv_left)).setText("部门");
        ((TextView) rl_setting3.findViewById(R.id.tv_left)).setText("电话");
        ((TextView) rl_setting4.findViewById(R.id.tv_left)).setText("工号");

        tv_right_nickname = (TextView) rl_setting1.findViewById(R.id.tv_right);
        tv_right_bm = (TextView) rl_setting2.findViewById(R.id.tv_right);
        tv_right_phone = (TextView) rl_setting3.findViewById(R.id.tv_right);
        tv_right_gh = (TextView) rl_setting4.findViewById(R.id.tv_right);
    }

    @Override
    protected void initData() {
        photoHelper = new PhotoHelper(this);
        tv_right_nickname.setText("" + SharedPreferencesUtils.getInstance().getString(Constant.NICKNAME));
        tv_right_bm.setText("" + SharedPreferencesUtils.getInstance().getString(Constant.DEPYNAME));
        tv_right_phone.setText("" + SharedPreferencesUtils.getInstance().getString(Constant.PHONE));
        tv_right_gh.setText("" + SharedPreferencesUtils.getInstance().getInt(Constant.USERGH));

        photoView = LayoutInflater.from(this).inflate(R.layout.dialog_photo, null);
        initDialog();
    }

    @OnClick({R.id.rl_setting_user_photo, R.id.rl_setting1, R.id.rl_setting2, R.id.rl_setting3, R.id.rl_setting4, R.id.login_out})
    public void onClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_setting_user_photo:
                requestPermission();
//                gotoOtherActivity(TestRefreshActivity.class);
                break;
            case R.id.rl_setting1://昵称
                gotoOtherActivity(UpNickNameActivity.class);
//                startActivity(new Intent(UserSettingActivity.this,UpNickNameActivity.class));
                break;
            case R.id.rl_setting2://部门
                break;
            case R.id.rl_setting3://电话
                gotoOtherActivity(UpPhoneActivity.class);
                break;
            case R.id.rl_setting4://工号
                break;
            case R.id.login_out://退出登录
                AppManager.getInstance().finishAllActivity();
                SharedPreferencesUtils.getInstance().remove(Constant.ISLOGIN);
                gotoOtherActivity(LoginActivity.class);
                finish();
                break;
        }
    }

    private void requestPermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            int checkCallPhonePermission = ContextCompat.checkSelfPermission(UserSettingActivity.this, Manifest.permission.CAMERA);
            if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(UserSettingActivity.this, new String[]{Manifest.permission.CAMERA,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE}, 100);
                return;
            } else {
                photoHelper.showDlg(1, 1);
            }
        } else {
            photoHelper.showDlg(1, 1);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 100) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                LogUtil.json("tongyi ");
                photoHelper.showDlg(1, 1);
            } else {
                LogUtil.json("butongyi");
            }
        }
    }

    private void takePhoto() {
        photoHelper.getFromCamera();
    }

    private void selPhoto() {
//        Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//        startActivityForResult(intent, 1002);
    }

    private void toastPhotoDialog() {
        alertDialog = new Dialog(this, R.style.MyDialogStyle);
        alertDialog.show();
        alertDialog.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
        alertDialog.getWindow().setGravity(Gravity.CENTER);
        alertDialog.getWindow().setWindowAnimations(R.style.bottomAnim);
        alertDialog.setCanceledOnTouchOutside(true);
        alertDialog.getWindow().setContentView(R.layout.dialog_photo);
        alertDialog.getWindow().findViewById(R.id.btn_take_photo).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                takePhoto();
            }
        });
        alertDialog.getWindow().findViewById(R.id.btn_pick_photo).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selPhoto();
            }
        });
        alertDialog.getWindow().findViewById(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.cancel();
            }
        });
    }

    private void initDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(UserSettingActivity.this);
        builder.setView(photoView);
        dialog = builder.create();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case HelperConstant.ALBUM:
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        File imgUri = new File(UriUtil.getFilePathFromURI(this, data.getData()));
                        photoHelper.startPhotoZoom(photoHelper.getUriForFile(imgUri));
                    } else {
                        photoHelper.startPhotoZoom(data.getData());
                    }
                    break;
                case HelperConstant.CAMERA:
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        //通过FileProvider创建一个content类型的Uri
                        photoHelper.startPhotoZoom(photoHelper.getUriForFile(photoHelper.getCameraFile()));
                    } else {
                        photoHelper.startPhotoZoom(Uri.fromFile(photoHelper.getCameraFile()));
                    }
                    break;
                case HelperConstant.CROP:
                    try {
                        Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(photoHelper.getCropUri()));
                        String path = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
                        picUrl = ImageUtils.saveAndgetMyBitmap(path, bitmap);

                        LogUtil.e(picUrl);
                        File picFile = new File(picUrl);
                        HashMap<String, RequestBody> param = new HashMap();
                        RequestBody photoRequestBody = RequestBody.create(MultipartBody.FORM, picFile);
                        param.put("file" + 0 + "\";filename=\"" + picFile.getName(), photoRequestBody);
                        param.put("imgNum", RequestBody.create(MediaType.parse("text/plain"), "1"));
                        APIClient.getInstance().getAPIService().PostImageAPI(Urls.uploadImg, param).
                                enqueue(new APICallback(this, new TypeToken<List<UserPhoto>>() {
                                }.getType(), 1));
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                    break;
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        tv_right_nickname.setText("" + SharedPreferencesUtils.getInstance().getString(Constant.NICKNAME));
    }

    @Override
    public void OnSuccessData(APIResponse apiResponse, Integer tag) {
        if (1 == tag) {
            List<UserPhoto> list = apiResponse.data.list;
            UserPhoto bean = list.get(0);
            String userPhoto = "";
            if (bean != null) {
                userPhoto = bean.getPath();
                SharedPreferencesUtils.getInstance().putString(Constant.HEADPATH, userPhoto);
            }

            FrescoUtil.setImg(this, iv_pic, HEAD_IMAGE + userPhoto);
            WebServiceApi.getInstance().upHeadImage(SharedPreferencesUtils.getInstance().getString("token"), userPhoto, this, 2);
        }
    }

    @Override
    public void OnErrorData(String code, Integer tag) {
        super.OnErrorData(code, tag);
    }

    @Override
    public void OnFailureData(String error, Integer tag) {
        super.OnFailureData(error, tag);
    }
}
